package net.cl.utils;

import java.io.File;
import java.lang.reflect.Array;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

public class XmlUtil {

	public static final String DEFAULT_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";

	public static String map2Xml(Map<String, Object> map) {
		StringBuilder sb = new StringBuilder();
		if (map == null)
			sb.append(map);
		else {
			sb.append("<item>");
			for (Iterator<Entry<String, Object>> iterator = map.entrySet().iterator(); iterator.hasNext();) {
				Entry<String, Object> entry = iterator.next();
				Object o = entry.getValue();
				if (o.getClass().isArray()) {
					sb.append("<").append(entry.getKey()).append("list").append(">");
					sb.append(array2Xml(o, entry.getKey()));
					sb.append("</").append(entry.getKey()).append("list").append(">");
				}
				else
					sb.append(object2Xml(o, entry.getKey()));
			}
			sb.append("</item>");
		}
		return sb.toString();
	}

	private static String array2Xml(Object array, String node) {
		StringBuilder sb = new StringBuilder();
		if (array == null) {
			sb.append(array);
			return sb.toString();
		}
		if (array.getClass().isArray()) {
			int length = Array.getLength(array);
			for (int i = 0; i < length; i++) {
				sb.append(object2Xml(Array.get(array, i), node));
			}
			return sb.toString();
		} else
			return StringUtil.EMPTY;
	}

	private static String object2Xml(Object obj, String node) {
		StringBuilder sb = new StringBuilder();
		if (obj == null)
			sb.append(obj);
		else {
			if (obj.getClass().isArray())
				return array2Xml(obj, node);
			else
				sb.append(wrap(node, obj.toString()));
		}
		return sb.toString();
	}

	private static String wrap(String node, String value) {
		return String.format("<%1$s>%2$s</%1$s>", node, value);
	}

	public static void main(String[] args) {
		Map map = new LinkedHashMap();
		map.put("name1", "Tom1");
		map.put("name2", "Tom2");
		map.put("name3", "Tom3");
		map.put("name4", new String[] { "Tom4", "Tom5", "Tom6" });
		String s = map2Xml(map);
		System.out.println(s);
		try {
			FileUtil.write(new File("D:/a.xml"), (String)null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
